<?php
// $Id$

/**
 * Controller_Cases controller
 */
class Controller_Cases extends Controller_Abstract
{
    function actionIndex()
    {
        // 确定查询条件
        $type = strtolower(trim($this->_context->type));
        $key = trim($this->_context->key);

        $conditions = array('is_approbated' => true);

        // 取得当前用户
        $user = $this->_app->currentUser();
        $this->_view['user'] = $user;

        $pagination_args = array();

        // 根据查询类型确定查询条件
        switch ($type)
        {
        case 'member':
            $conditions['owner.username'] = $key;

            // 如果是显示当前登录用户的案例，则同时显示未通过审核的案例
            if (!empty($user['username']) && $user['username'] == $key)
            {
                unset($conditions['is_approbated']);
            }
            break;
        default:
            $type = null;
        }

        if ($type)
        {
            $pagination_args['type'] = $type;
            $pagination_args['key']  = $key;
        }

        // 确定排序规则
        $order = strtolower(trim($this->_context->order));
        if ($order)
        {
            // 检查排序规则是否有效
            $order = Q::normalize(strtolower($order), '-');
            if (in_array($order[0], array('clicks_count', 'rating', 'updated')))
            {
                $order_key = $order[0];
                $order_dir = (isset($order[1]) && strtolower($order[1]) == 'desc') ? 'DESC' : 'ASC';
                $pagination_args['order'] = "{$order_key}-{$order_dir}";
                $order = "{$order_key} {$order_dir}";
            }
            else
            {
                $order = null;
            }
        }

        if (!$order)
        {
            $order = 'created DESC';
            $pagination_args['order'] = 'created-DESC';
        }

        // 分页查询
        $page = intval($this->_context->page);
        if ($page < 1) $page = 1;
        $select = UserCase::find($conditions)->limitPage($page, Q::ini('appini/site/items_pagination'))->order($order);
        $this->_view['pagination'] = $select->getPagination();
        $this->_view['pagination_args'] = $pagination_args;
        $this->_view['cases'] = $select->query();
    }

    /**
     * 显示指定案例的详情
     */
    function actionShow()
    {
        $user = $this->_app->currentUser();
        $this->_view['user'] = $user;

        $id = strtolower(trim($this->_context->id));
        $case = UserCase::find('[id] = ? AND (is_approbated = ? OR member_id = ?)', $id, true, $user['id'])->query();
        if (!$case->id())
        {
            return $this->_redirect(url('cases/index'));
        }
        $case->clicks_count++;
        $case->save();
        $this->_view['case'] = $case;
    }

    /**
     * 创建新案例
     */
    function actionCreate()
    {
        $form = Form_UserCase::createForm(url('cases/create'));
        $form->_cancel_url = url('cases/index', array(
            'type' => 'member',
            'key' => $this->_app->currentUserObject()->username)
        );

        if ($this->_context->isPOST() && $form->validate($_POST))
        {
            // 如果是 POST 请求，并且提交的表单通过验证，则创建对象
            try
            {
                $case = new UserCase($form->values());
                $case->owner = $this->_app->currentUserObject();
                $case->save();
                return $this->_redirect(url('cases/edit', array('id' => $case->id())));
            }
            catch (QValidator_ValidateFailedException $ex)
            {
                // 如果保存时抛出了验证失败异常，则将表单置为无效状态
                $form->invalidate($ex);
            }
        }

        $this->_view['form'] = $form;
    }

    /**
     * 编辑已有的案例
     */
    function actionEdit()
    {
        $id = intval($this->_context->id);
        // 查询时限定当前用户，可以避免提交非法数据篡改其他用户的案例信息
        $case = UserCase::find('[id] = ? AND member_id = ?',
            $id,
            $this->_app->currentUserObject()->id())
        ->query();

        if (!$case->id())
        {
            return $this->_redirect(url('cases/index'));
        }

        $form = Form_UserCase::createForm(url('cases/edit', array('id' => $case->id())), 'edit');
        $form->enableSkipUpload();
        $form->_cancel_url = url('cases/show', array('id' => $case->id()));

        if ($this->_context->isPOST() && $form->validate($_POST))
        {
            // 如果是 POST 操作，并且表单通过验证，则更新已有的对象
            try
            {
                $case->changeProps($form->values());
                $next_action = 'show';
                if ($form['is_pending_delete']->value() && !$case->is_pending_delete)
                {
                    // 申请删除
                    $case->pendingDelete();
                    $next_action = 'pending_delete';
                }
                elseif ($case->is_pending_delete && !$form['is_pending_delete']->value())
                {
                    // 取消删除
                    $case->pendingDelete(false);
                    $next_action = 'cancel_delete';
                }

                $case->save();

                if ($next_action == 'pending_delete')
                {
                    return $this->_redirectMessage(
                        '提示信息',
                        '您的案例删除请求已经提交，管理员审核后将尽快处理。',
                        url('cases/show', array('id' => $case->id())));
                }

                if ($next_action == 'cancel_delete')
                {
                    return $this->_redirectMessage(
                        '提示信息',
                        '您的案例删除请求已经取消。',
                        url('cases/show', array('id' => $case->id())));
                }

                return $this->_redirect(url('cases/edit', array('id' => $case->id())));
            }
            catch (QValidator_ValidateFailedException $ex)
            {
                $form->invalidate($ex);
            }
        }
        elseif (!$this->_context->isPOST())
        {
            $form->import($case);
            $form['is_pending_delete']->checked = $case->is_pending_delete;
        }
        else
        {
            $form['is_pending_delete']->checked = $form['is_pending_delete']->value;
        }

        $this->_view['case'] = $case;
        $this->_view['form'] = $form;
    }


    /**
     * 删除案例文件
     */
    function actionDeletePic()
    {
        // 只允许删除自己案例的文件
        $id = intval($this->_context->id);
        $pic = intval($this->_context->pic);
        $user = $this->_app->currentUser();
        if (!empty($user))
        {
            $query = '[id] = ? AND [case.id] = ? AND [case.member_id] = ?';
            UserCasePicture::meta()->destroyWhere($query, $pic, $id, $user['id']);
        }

        return $this->_redirect(url('cases/edit', array('id' => $id)));
    }
}

